#include "Client.h"


#include <iostream>
using namespace std;


int Client::run()
{

	m_connection.start();

	unsigned int connectionID = 0;

	while (!m_bTerminate)
	{
		// accept new connections and create a new thread for each one
		SOCKET s1 = accept(m_listeningSocket, NULL, NULL);
		if (s1==INVALID_SOCKET) {
			cerr << "Accept failed with " << WSAGetLastError() << endl;
		}


		Connection conn;
		conn.start(s1, connectionID);
		connectionID++;
	}
	return 0;
}



int Client::init()
{
	// Create version identifier
	WORD wVersionRequested = MAKEWORD( 2, 0 );

	// Startup windows sockets
	WSADATA wsaData;
	if ( WSAStartup( wVersionRequested, &wsaData )) {
		cerr << "Socket initialisation failed" << endl;
		return -1;
	}

	// Create socket data space
	sockaddr_in peer;
	peer.sin_family = AF_INET;
	peer.sin_port = htons(9171);	// port 9171
	peer.sin_addr.S_un.S_addr = inet_addr( "127.0.0.1" );

	// Create transfer socket
	char buffer;
	SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
	if (s==INVALID_SOCKET) {
		cerr << "Create socket failed" << endl;
	} 
	else if (connect(s, (sockaddr *)&peer, sizeof(peer))==SOCKET_ERROR) {
		cerr << "Connect to peer failed with " << WSAGetLastError() << endl;
	}

	return 0;
}